package love.yuanmengrobot.qianyugarden.controller;
/*
 *   @Studio:CHJY · 源梦科技
 *   @Author:CHJY创幻
 *   @Ide:IntelliJ IDEA
 *   @Creation time:2021/7/20 14:27
 */

import love.yuanmengrobot.qianyugarden.entity.*;
import love.yuanmengrobot.qianyugarden.service.BookService;
import love.yuanmengrobot.qianyugarden.service.ThousandLanguageService;
import love.yuanmengrobot.qianyugarden.utils.AppFileUtils;

import love.yuanmengrobot.qianyugarden.utils.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;

@Controller
public class UploadController {
    @Autowired
    BookService bookService;
    @Autowired
    ThousandLanguageService thousandLanguageService;
    Book book;
    BookLabels[] bookLabels;
    BookEvent bookEvent;

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    @GetMapping("/upload")
    public String upload(ModelMap map) {

        map.put("css_upBook", "css/upBook/upBook.css");
        map.put("js_upBook", "js/upBook/upBook.js");
        map.put("lanList", thousandLanguageService.queryAllByType("语言"));
        map.put("frameList", thousandLanguageService.queryAllByType("框架"));

        return "upBook/upBook.html";
    }

    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }

        String fileName = file.getOriginalFilename();//获取文件名字
        String fileSuffix = "";//后缀
        String fileSize = "";//大小
        //获取文件后缀
        int lastIndex = fileName.lastIndexOf(".");
        if (lastIndex != -1) {
            fileSuffix = fileName.substring(lastIndex + 1, fileName.length());
        }
        DecimalFormat decimalFormat = new DecimalFormat(".00");
//format 返回的是字符串
        //文件大小，调整精度
        Long len = file.getSize();
//        if (len < 1024) {
//            fileSize = len + "字节";
//        } else if (len > 1024 && len < 1024 * 1024) {
//            fileSize = decimalFormat.format(len / 1024.0) + "k";
//        } else if (len > 1024 * 1024) {
        fileSize = decimalFormat.format(len / 1024.0 / 1024);
//        }
//        fileSize=String.valueOf(len);
        System.out.println("文件原名：" + fileName);
        System.out.println("后缀：" + fileSuffix);
        System.out.println("大小：" + fileSize);
        String fileMainName = AppFileUtils.createBookFileName(fileName);
        System.out.println("添加主键后的文件名：" + fileMainName);

        //获取form值
        String language = request.getParameter("tlInput");//选择的语言
        String labelList = request.getParameter("tlLableInput");//标签列表，以；隔开
        String bookTitle = request.getParameter("bookTitle");//书籍标题
        String bookDesc = request.getParameter("bookDesc");//书籍简介
        String bookCredit = request.getParameter("bookCredit");//书籍积分

        //设置实列
        book = new Book();
        book.setObjectid(RandomUtils.createIdOX("BF"));
        book.setType(fileSuffix);
        book.setName(bookTitle);
        book.setK(fileSize);
        book.setUserid(getUserId(request));
        book.setCreatetime(RandomUtils.getTime());
        book.setIntegral(Integer.parseInt(bookCredit));
        book.setStatus("发布");//默认
        book.setDescBook(bookDesc);
        book.setHref(fileMainName);//该链接地址可下载文件
        System.out.println("书籍：" + book);

        //设置书籍的标签,语言标签
        BookLabels[] bookLabelsFour = new BookLabels[4];
        int bookLenght = 0;

        BookLabels bookLabels = new BookLabels();
        bookLabels.setObjectid(RandomUtils.createIdOX("BL"));
        ThousandLanguage thousandLanguage = thousandLanguageService.queryByName(language);
        if (thousandLanguage != null && thousandLanguage.getObjectid() != null) {
            bookLabels.setThousandlanguageid(thousandLanguage.getObjectid());
        }
        bookLabels.setBookid(book.getObjectid());
        bookLabelsFour[bookLenght] = bookLabels;
        bookLenght++;


        //获取标签数组，设置框架标签
        String[] la = labelList.split(";");
        System.out.println("长度：" + la.length);
        for (String s : la) {
            if (s == null || s.length() <= 0) continue;
            else {
                System.out.println("分割结果：" + s);
                BookLabels bookLabel = new BookLabels();
                thousandLanguage = thousandLanguageService.queryByName(s);
                if (thousandLanguage != null && thousandLanguage.getObjectid() != null) {
                    bookLabel.setThousandlanguageid(thousandLanguage.getObjectid());
                } else
                    continue;
                bookLabel.setObjectid(RandomUtils.createIdOX("BL"));
                bookLabel.setBookid(book.getObjectid());
                bookLabelsFour[bookLenght] = bookLabel;
                bookLenght++;
                if (bookLenght >= 4) continue;
            }
        }
        bookEvent = new BookEvent();
        bookEvent.setObjectid(RandomUtils.createIdOX("BE"));
        bookEvent.setBookid(book.getObjectid());
        bookEvent.setObservations(0);
        bookEvent.setLikes(0);
        bookEvent.setDownloads(0);
        bookEvent.setCollections(0);

        try {

//            文件写入
            File dest = new File(AppFileUtils.bookfilePath + "\\" + fileMainName);
            file.transferTo(dest);


            bookService.insertAndLabelAndEvent(book, bookLabelsFour, bookEvent);


            LOGGER.info("上传成功");
            return "上传成功";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        LOGGER.info("上传失败");
        return "上传失败！";
    }

    public String getUserId(HttpServletRequest request) {

        HttpSession session = request.getSession(false);
        if (session != null) {
            User user = (User) session.getAttribute("UserInfo");
            if (user != null) {
                return user.getObjectid();

            }
        }
        return null;
    }

}